<template>
	<view class="content">
		<view class="cropper-wrapper" style="height:617px">
			<canvas
				class="cropper"
				disable-scroll="true"
				@touchstart="touchStart"
				@touchmove="touchMove"
				@touchend="touchEnd"
				:style="{ width: cropperOpt.width, height: cropperOpt.height }"
				canvas-id="cropper"
			></canvas>
		</view>
		<view class="cropper-buttons">
			<view class="upload" @tap="uploadTap">重新选择</view>
			<view class="getCropperImage" @tap="getCropperImage">确定</view>
		</view>
	</view>
</template>

<script>
import weCropper from '@/common/js/weCropper';
const device = uni.getSystemInfoSync();
const width = device.windowWidth;
const height = device.windowHeight - 50;
export default {
	data() {
		return {
			cropperOpt: {
				id: 'cropper',// 用于手势操作的canvas组件标识符
				width: width,
				height: height,
                pixelRatio: device.pixelRatio, // 传入设备像素比
				scale: 8,// 最大缩放倍数
				zoom: 18,// 缩放系数
				cut: {
					x: (width - 300) / 2,
					y: (height - 300) / 2,
					width: 300,
					height: 300
				}
			},
			weCropper: ''
		};
	},
	methods: {
		touchStart(e) {
			this.weCropper.touchStart(e);
		},
		touchMove(e) {
			this.weCropper.touchMove(e);
		},
		touchEnd(e) {
			this.weCropper.touchEnd(e);
		},
		convertBase64UrlToBlob(dataURI, type) {
			var binary = atob(dataURI.split(',')[1]);
			var array = [];
			for (var i = 0; i < binary.length; i++) {
				array.push(binary.charCodeAt(i));
			}
			return new Blob([new Uint8Array(array)], { type: type }, { filename: '1111.jpg' });
		},
		blobToDataURL(blob) {
			var a = new FileReader();
			a.readAsDataURL(blob); //读取文件保存在result中
			a.onload = function(e) {
				var getRes = e.target.result; //读取的结果在result中
				console.log(getRes);
			};
		},
		getCropperImage() {
			uni.showLoading({
				title:'请稍后'
			})
			let _this = this;
			let pathurl = this.$Config('APIHOST')+this.$api.common.upload;//上传服务器地址
			this.weCropper.getCropperImage(avatar => {
				if (avatar) {
					//下面是上传到服务器的方法
					uni.uploadFile({
						url: pathurl,
						filePath: avatar,
						name: 'file[]',
						success: res => {
							uni.hideLoading()
                            var rescult = JSON.parse(res.data);
							uni.showToast({
								title: '上传成功',
								icon: 'success',
								duration: 1000
							});
							//  获取到裁剪后的图片
							uni.$emit('upHeadImg',{
								avatar: rescult.data[0].path,
								path: rescult.data[0].id
							})
							uni.navigateBack();
                            //  获取到裁剪后的图片  方法二，旧
                            // wx.redirectTo({
                            //   url: '/pages/center/usersetting?avatar='+ avatar +'&path=' + rescult.data[0].path
                            // })
						},
						fail: err => {
							console.log('uploadImage fail', err);
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
							uni.hideLoading();
						},
						complete: () => {
							console.log('complate');
						}
					});
				} else {
					console.log('获取图片失败，请稍后重试');
				}
			});
		},
		uploadTap() {
			var _this = this
			// #ifdef APP-PLUS
			plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'], function(e) {
			
				var result = 0;
				for (var i = 0; i < e.granted.length; i++) {
					var grantedPermission = e.granted[i];
					console.log('已获取的权限：' + grantedPermission);
					result = 1
				}
				for (var i = 0; i < e.deniedPresent.length; i++) {
					var deniedPresentPermission = e.deniedPresent[i];
					console.log('拒绝本次申请的权限：' + deniedPresentPermission);
					result = 0
				}
				for (var i = 0; i < e.deniedAlways.length; i++) {
					var deniedAlwaysPermission = e.deniedAlways[i];
					console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
					result = -1
				}
				console.log(result);
				if(result === 1){
					uni.chooseImage({
						count: 1, // 默认9
						sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
						success(res) {
							let src = res.tempFilePaths[0];
							//  获取裁剪图片资源后，给data添加src属性及其值
							_this.weCropper.pushOrign(src);
						}
					});
				}else if (result === 0){
					uni.showModal({
						title: '亲爱的用户',
						content: '您需要打开相册权限，才能使用完整功能。若您需要，请点击同意，重新授权',
						success(res) {
							if (res.confirm) {
								plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'])
							}
						}
					});
				}else{
					uni.showModal({
						title: '提示',
						content: '相册授权已被拒绝，请前往设置打开应用相册权限',
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								var main = plus.android.runtimeMainActivity();  
								var Intent = plus.android.importClass("android.content.Intent");
								var mIntent = new Intent('android.settings.WIRELESS_SETTINGS');  
								main.startActivity(mIntent); 
							}
						}
					});
				}
			}, function(e) {
				console.log('Request Permissions error:' + JSON.stringify(e));
			});
			// #endif
			// #ifdef MP
			uni.chooseImage({
				count: 1, // 默认9
				sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success(res) {
					let src = res.tempFilePaths[0];
					//  获取裁剪图片资源后，给data添加src属性及其值
					_this.weCropper.pushOrign(src);
				}
			});
			// #endif
			
		}
	},
	onLoad(option) {
		// do something
		const cropperOpt = this.cropperOpt;
		const src = option.src;
		if (src) {
			Object.assign(cropperOpt, {
				src
			});
			this.weCropper = new weCropper(cropperOpt)
				.on('ready', function(ctx) {})
				.on('beforeImageLoad', ctx => {
					uni.showToast({
						title: '上传中',
						icon: 'loading',
						duration: 3000
					});
				})
				.on('imageLoad', ctx => {
					uni.hideToast();
				});
		}
	}
};
</script>

<style>
.content {
	background: rgba(255, 255, 255, 1);
}

.head-list {
	height: 43px;
	width: 100%;
	background: #ffffff;
	justify-content: center;
	align-items: center;
	display: flex;
	border-bottom: 1px solid rgba(244, 244, 244, 1);
}

.head-info {
	text-align: center;
	font-size: 18px;
	color: #000000;
	font-weight: bold;
}

.save-box {
	position: absolute;
	right: 0px;
	width: 50px;
	height: 43px;
	line-height: 43px;
}

.save {
	color: rgba(98, 111, 252, 1);
	font-size: 16px;
	font-weight: 400;
}

.icon-back {
	margin-top: 11px;
	width: 10px;
	height: 18px;
	color: #000000;
	margin-left: 6px;
}

.icon-back-box {
	display: block;
	position: absolute;
	left: 6px;
	height: 43px;
	width: 30px;
	align-items: center;
}
.cropper {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
}

.cropper-buttons {
	background-color: rgba(0, 0, 0, 0.95);
	color: #04b00f;
}
.cropper-wrapper {
	position: relative;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	width: 100%;
	background-color: #F0F0F0;
}

.cropper-buttons {
	width: 100vw;
	height: 50px;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	position: fixed;
	bottom: 0;
	left: 0;
	line-height: 50px;
}

.cropper-buttons .upload,
.cropper-buttons .getCropperImage {
	width: 50%;
	text-align: center;
    color: #fff;
}
</style>
